import time

import peewee as pw
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

from awesomest_spider import glb


class Douban(glb.Model):
    name = pw.CharField(primary_key=True)
    link = pw.CharField()
    rate = pw.CharField()
    abstract = pw.CharField()
    stars = pw.CharField()


def main(keyword):
    # 1.定义浏览器
    driver = webdriver.Chrome()
    # 输入网址
    driver.get('https://movie.douban.com')
    # 定位搜索框
    input_tag = driver.find_element_by_id('inp-query')
    # 模拟输入搜索
    input_tag.send_keys(keyword)
    input_tag.send_keys(Keys.ENTER)
    # 加载时间
    time.sleep(5)
    movies = driver.find_elements_by_class_name('item-root')
    for movie in movies:
        movie_link = movie.find_element_by_tag_name('a').get_attribute('href')
        movie_name = movie.find_element_by_css_selector('.title a').text
        try:
            movie_score = movie.find_element_by_class_name('rating_nums').text
        except NoSuchElementException:
            movie_score = '暂无评分'
        movie_abstract = movie.find_element_by_class_name('abstract').text
        movie_abstract_2 = movie.find_element_by_class_name('abstract_2').text
        data = {
            'name': movie_name,
            'link': movie_link,
            'rate': movie_score,
            'abstract': movie_abstract,
            'stars': movie_abstract_2,
        }
        Douban.replace(data).execute()
        yield data
    driver.quit()


model = Douban
if __name__ == '__main__':
    for i in main(input('请输入需要在豆瓣爬取的内容（演员，电影名）：')):
        print(i)
